<template>
  <div class="global_company_info main_white marginTop10">
    <div class="mainua_form">
      <el-form
        :inline="false"
        :model="wechat_form"
        class="demo-form-inline"
        ref="userListFrom"
        label-width="140px"
      >
        <el-form-item label="公众号二维码:" prop="pic">
          <div class="main_upImg marginTop5">
            <el-upload
              :action="uploadPath"
              list-type="picture-card"
              :on-success="(value) => handSuccess(1, value)"
              :show-file-list="false"
              :data="uploadparams"
            >
              <span slot="default">
                <svg
                  aria-hidden="true"
                  class="main_page_svg"
                  width="32"
                  height="27"
                >
                  <use xlink:href="#icon-commodit_camera" />
                </svg>
              </span>
            </el-upload>
            <img
              v-if="wechat_form.wx_pic"
              :src="wechat_form.wx_pic"
              class="main_avatar"
            />
            <div class="clearfix"></div>
          </div>
          <div class="global_cu">建议尺寸（120*120）</div>
        </el-form-item>
        <el-form-item label="公众号appid:" prop="site_title">
          <div class="upload_item">
            <el-input
              v-model="wechat_form.wx_appId"
              placeholder="公众号appid"
            ></el-input>
            <div style="max-width: 400px; margin-left: 5px">
              <el-upload
                :action="uploadTxt"
                :on-success="handSuccessTxt"
                :show-file-list="true"
                :before-upload="beforeUpload"
                :file-list="fileList"
                :limit="1"
              >
                <!-- :data="uploadparams" -->
                <div style="display: flex; align-items: center">
                  <el-button size="small" type="success"
                    >上传验证文件</el-button
                  >
                  <div slot="tip" class="el-upload__tip">
                    只能上传一个.txt文件，且不超过1kb
                  </div>
                </div>
              </el-upload>
              <div class="clearfix"></div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="公众号appsecret" prop="site_phone">
          <el-input
            v-model="wechat_form.wx_appSecret"
            placeholder="公众号appsecret"
          ></el-input>
        </el-form-item>
        <el-form-item label="小程序太阳码:" prop="pic">
          <div class="main_upImg marginTop5">
            <el-upload
              :action="uploadPath"
              list-type="picture-card"
              :on-success="(value) => handSuccess(2, value)"
              :show-file-list="false"
              :data="uploadparams"
            >
              <span slot="default">
                <svg
                  aria-hidden="true"
                  class="main_page_svg"
                  width="32"
                  height="27"
                >
                  <use xlink:href="#icon-commodit_camera" />
                </svg>
              </span>
            </el-upload>
            <img
              v-if="wechat_form.mini_pic"
              :src="wechat_form.mini_pic"
              class="main_avatar"
            />
            <div class="clearfix"></div>
          </div>
          <div class="global_cu">建议尺寸（120*120）</div>
        </el-form-item>
        <el-form-item label="小程序appid:" prop="site_title">
          <el-input
            v-model="wechat_form.mini_appId"
            placeholder="小程序appid"
          ></el-input>
          <!-- 小程序上传 -->
          <el-button
            size="small"
            type="success"
            :loading="publish_loading"
            @click="publishMiniApp"
            >{{ publish_content }}</el-button
          >
        </el-form-item>
        <el-form-item label="小程序appsecret" prop="site_phone">
          <el-input
            v-model="wechat_form.mini_appSecret"
            placeholder="小程序appsecret"
          ></el-input>
        </el-form-item>
        <!-- 分享 -->
        <el-form-item label="分享图标:" prop="pic">
          <div class="main_upImg marginTop5">
            <el-upload
              :action="uploadPath"
              list-type="picture-card"
              :on-success="(value) => handSuccess(3, value)"
              :show-file-list="false"
              :data="uploadparams"
            >
              <span slot="default">
                <svg
                  aria-hidden="true"
                  class="main_page_svg"
                  width="32"
                  height="27"
                >
                  <use xlink:href="#icon-commodit_camera" />
                </svg>
              </span>
            </el-upload>
            <img
              v-if="wechat_form.share_img"
              :src="wechat_form.share_img"
              class="main_avatar"
            />
            <div class="clearfix"></div>
          </div>
          <!-- <div class="global_cu">建议尺寸（120*120）</div> -->
        </el-form-item>
        <el-form-item label="分享标题:" prop="share_title">
          <el-input
            v-model="wechat_form.share_title"
            placeholder="分享标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="分享描述:" prop="share_describe">
          <el-input
            v-model="wechat_form.share_describe"
            placeholder="分享描述"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
          ></el-input>
        </el-form-item>
        <el-form-item label="分享链接:" prop="share_href">
          <el-input
            v-model="wechat_form.share_href"
            placeholder="分享链接"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-dialog
        title="微信小程序上传"
        :visible.sync="upWxdialogVisible"
        width="800px"
        @close="handclose"
        @open="handleopen"
        @closed="handleclosed"
      >
        <div>
          <upload-wx-miniapp
            ref="uploadWxMiniApp"
            v-if="shoWuploadWxMiniApp"
            :app_id="wechat_form.mini_appId"
            :wx_miniapp_data="wx_miniapp_data"
            :pro="pro"
          ></upload-wx-miniapp>
        </div>
        <span slot="footer" class="dialog-footer">
          <!-- <el-button @click="upWxdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="upWxdialogVisible = false"
            >确 定</el-button
          > -->
        </span>
      </el-dialog>
      <div class="clearfix"></div>
      <div class="newConBox_p100 paddingBottom10" id="newConBox">
        <div class="newConBox_h32">
          <div
            :class="[
              'mainua_an newConBox ',
              { on: searchBarFixed },
              { marginLeft5: !searchBarFixed },
            ]"
          >
            <el-button type="primary" @click="preservation" v-repeatClick
              >保存</el-button
            >
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { uploadPath, uploadTxt } from "@/api/currency";
import { setting_info } from "@/api/global/globalSystem";
import { setting_company } from "@/api/currency";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import UploadWxMiniapp from "./components/uploadWxMiniapp.vue";
import { getRelease, getAuditStatus } from "@/api/global/globalUploadWxApp";

export default {
  components: {
    UploadWxMiniapp,
  },
  props: {
    form: {
      type: Object,
      required: true,
    },
  },
  watch: {
    form(newval, oldval) {
      this.wechat_form = newval;
    },
  },
  computed: {
    ...mapGetters(["avatar"]),
  },
  data() {
    return {
      // 上传图片
      uploadPath,
      uploadTxt,
      fileList: [],
      wechat_form: {
        wx_pic: "",
        wx_appId: "",
        wx_appSecret: "",
        mini_pic: "",
        mini_appId: "",
        mini_appSecret: "",
        share_title: "",
        share_img: "",
        share_describe: "",
        share_href: "",
      },

      // 监听滚动
      searchBarFixed: false,
      // 上传图片参数
      uploadparams: {
        store: "wxqrcode",
      },
      // 上传微信小程序
      upWxdialogVisible: false,
      publish_content: "小程序发布",
      publish_loading: false,
      // 小程序发布查询
      wx_miniapp_data: {
        is_publish: false,
        audit: {},
      },
      pro: {
        name: "zhangasn",
        age: 1,
      },
      shoWuploadWxMiniApp: false,
    };
  },
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
    this.wechat_form = this.form;
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    // 监听滚动
    handleScroll() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      scrollTop + document.documentElement.clientHeight >
      document.getElementById("newConBox").offsetTop + 300
        ? (this.searchBarFixed = false)
        : (this.searchBarFixed = true);
    },
    // 上传图片-成功
    handSuccess(type, res, file, fileList) {
      if (type == 1) {
        this.wechat_form.wx_pic = res.data.src;
      } else if (type == 2) {
        this.wechat_form.mini_pic = res.data.src;
      } else if (type == 3) {
        this.wechat_form.share_img = res.data.src;
      } else if (type == 4) {
        if (res.errcode == 0) {
          this.$message.success("上传成功");
        } else {
          this.$message.error(res.errmsg);
          fileList = [];
        }
      }
    },
    handSuccessTxt(res, file, fileList) {
      if (res.errcode == 0) {
        this.$message.success("上传成功");
        this.fileList = fileList;
      } else {
        this.$message.error(res.errmsg);
        this.fileList = [];
      }
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 1 / 1024;
      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过 1kb!");
        return false;
      }
      let type = file.type;
      let typeList = ["text/plain"];
      if (typeList.indexOf(type) == -1) {
        this.$message.error("上传文件需要为.txt后缀文件!");
        return false;
      }
      return isLt2M;
    },
    // 保存
    async preservation() {
      let res = await this.$emit("save", { data: this.wechat_form });
    },
    // 发布小程序
    async publishMiniApp() {
      if (!this.wechat_form.mini_appId && !this.wechat_form.mini_appSecret) {
        this.$message.error("请先填写【小程序appID】和【appsecret】并保存");
        return;
      }
      this.publish_loading = true;
      this.publish_content = "状态查询中";
      let result = await this.getStatus();
      if (result == 1) {
        this.upWxdialogVisible = true;
      } else if (result == 0) {
      }
      this.publish_loading = false;
      this.publish_content = "小程序发布";
    },
    getStatusDemo() {
      let demo1 = new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve("dem1");
        }, 500);
      });
      let demo2 = new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log("demo2");
          resolve("dem2");
        }, 1000);
      });
      return Promise.all([demo1, demo2]).then((res) => {
        console.log("res", res);
        this.pro.age++;

        return 1;
      });
    },
    // 查询审核和发布状态
    getStatus() {
      let data = {
        app_id: this.wechat_form.mini_appId,
      };
      let AuditStatus = new Promise((resolve, reject) => {
        getAuditStatus(data)
          .then((res) => {
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
      let Release = new Promise((resolve, reject) => {
        getRelease(data)
          .then((res) => {
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
      return Promise.all([Release, AuditStatus])
        .then((res) => {
          let publish = res[0];
          let audit = res[1];
          if (publish.errcode == 0) {
            this.wx_miniapp_data.is_publish = true;
          } else if (publish.errcode == 40011) {
            // this.$message.error(publish.errmsg);
          } else if (publish.errcode == 40016) {
            this.$message.error(publish.errmsg);
            return Promise.resolve(0);
          }
          this.wx_miniapp_data.audit = audit;
          return Promise.resolve(1);
        })
        .catch((error) => {
          this.$message.error("小程序状态查询失败");
          return Promise.resolve(0);
        });
    },
    handclose() {
      this.$refs.uploadWxMiniApp.clearTime();
    },
    handleopen() {
      this.shoWuploadWxMiniApp = true;
    },
    handleclosed() {
      this.shoWuploadWxMiniApp = false;
    },
  },
  created() {},
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";

.global_company_info {
  .mainua_form {
    .mainua_an {
      /deep/.el-form-item__content {
        margin-left: 0px !important;
      }
      .reset {
        background: $subActive;
        color: $menuText;
        border-color: $subActive;

        &:hover,
        &:focus {
          border-color: $menuActiveText;
          color: $menuActiveText;
        }
      }
    }
  }
  padding: 10px 10px 10px 10px;
  margin: 0 15px 0 15px;
  /deep/.el-input {
    width: 400px;
  }
  /deep/.el-textarea__inner {
    width: 600px !important;
    height: 200px;
  }
  .global_cu {
    font-size: 12px;
    color: #eb0a0a;
    margin-top: -10px;
    padding-left: 7px;
  }
}
.upload_item {
  display: flex;
  align-items: flex-start;
}
/deep/ .el-upload__tip {
  margin-top: 0;
  padding-left: 8px;
}
</style>
